import { equals } from "../equals";
import { isHas } from "../isHas";
import { isObject } from "../isObject";

export interface ValueTypes<T> {
  current: T;
}

// 表示 摒弃的参数
export interface MissOptions {
  value: boolean;
}

// 表示 默认的参数
export const defaultMissOptions: MissOptions = {
  value: true,
};

/**
 * @description 这是一个class target类包裹器
 * @author lihh
 */
class TargetWrapper<T = string> {
  private v: T;
  private missOptions: MissOptions;

  constructor(v: T, missOptions: MissOptions) {
    this.v = v;
    this.missOptions = missOptions;
  }

  get current() {
    return isObject(this.v) && isHas(this.v, "value") && !this.missOptions.value
      ? (this.v.value as T)
      : this.v;
  }

  set current(v1: T) {
    if (isObject(this.v) && isHas(this.v, "value") && !this.missOptions.value) {
      (this.v as unknown as { value: T }).value = v1;
    } else {
      this.v = v1;
    }
  }
}

/**
 * @description 模拟 react 的useState hook状态
 * @param initialValue 初期化值
 * @param missOptions 错误的 miss options
 * @author lihh
 */
export function useState<T = string>(
  initialValue: T,
  missOptions?: MissOptions
): [ValueTypes<T>, (v: T) => void] {
  const mergeMissOptions = Object.assign(
    {},
    defaultMissOptions,
    missOptions || {}
  );
  // 这里定义一个包裹器
  const state: TargetWrapper<T> = new TargetWrapper(
    initialValue,
    mergeMissOptions
  );

  const setState = (v: T) => {
    if (equals(state.current, v)) {
      return;
    }
    state.current = v;
  };

  return [state, setState];
}
